<!--
 * @Description: Description
 * @Author: Kerwin
 * @Date: 2025-04-29 14:23:32
 * @LastEditTime: 2025-08-27 15:43:48
 * @LastEditors:  Please set LastEditors
-->

<template>
  <view class="rf-search-bar bg-primary">
    <view class="header">
      <!-- 搜索框 -->
      <!-- logo -->
      <image
        style="width: 120rpx; height: 50rpx; margin-left: 10rpx"
        :src="getLogo()"
        mode="scaleToFill"
      />
      <view class="input-box">
        <!-- 城市 -->
        <view @click="openSelector" class="city-box">
          {{ getAdr?.cityName || '定位中' }}
          <u-icon
            class="icon"
            :class="{ 'rotate-icon': selectorShow }"
            name="arrow-down-fill"
            size="24"
            color="#000"
          ></u-icon>
          <text style="color: #b5b5b5; margin: 40rpx">|</text>
        </view>
        <text class="iconfont hy-icon-search"></text>
        <input
          @input="debouncedHandleSearch"
          v-model="searchText"
          placeholder="请输入餐厅名"
          style="width: 300rpx"
          class="input"
        />
      </view>
    </view>
    <u-select
      v-model="selectorShow"
      mode="mutil-column-auto"
      :list="cityList"
      :default-value="selectDefault"
      @confirm="selectorConfirm"
    ></u-select>
  </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { reactive, ref, watch, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { getQueryObject } from '@/utils/common'
import { useUserStore } from '@/store'
import { getLocation, getWZLocation } from '@/utils'
import { baseApi } from '@/api'
import { jsSdkConfig, scanQRCode } from '@/common/wechat-share' // 引入 scanQRCode
import debounce from 'lodash/debounce'
//图片
import log1 from '@/static/log1.png'
import log4 from '@/static/log4.png'
import log6 from '@/static/log6.png'

// 初始数据
//interface
interface Address {
  cityShortName?: string
  cityName?: string
  districtName?: string
  provinceName?: string
  provinceId?: number
  cityId?: number
  districtId?: number
}

// props
const props = withDefaults(
  defineProps<{
    placeholder?: string
    icon?: string
    topDistance?: number
    address?: Address
  }>(),
  {
    placeholder: '请输入餐厅名',
    icon: 'hy-icon-scan',
    topDistance: 0,
    address: () => ({}) // 对象类型默认值应使用函数返回
  }
)
const userStore = useUserStore()
const getAdr = ref<any>({}) //传递的地址
const emit = defineEmits(['onSearch', 'onAddressChange'])

const clientInfo = reactive({
  width: 0,
  height: 0,
  inputTop: 0
})
const wzAddress = ref<any>()
const searchText = ref('')
const selectorShow = ref(false)

const address = ref<Address>()
async function getCurrentCity() {
  const location = await getLocation(true)
  const { data } = await baseApi.reverseGeocoding(location)
  address.value = addressFormat(data)
  uni.setStorageSync('currentAddress', address.value)
}
function addressFormat(address: Address): Address {
  if (
    typeof address === 'undefined' ||
    address === null ||
    JSON.stringify(address) === '{}'
  ) {
    return {}
  }
  if (typeof address.cityName !== 'undefined' && address.cityName !== null) {
    address.cityShortName = address.cityName.split('市')[0]
  }
  return address
}
// getCurrentCity()

const cityList = ref<object[]>([])
interface Area {
  id: string
  name: string
  parentId: string
  deep: number
}
function partTree(tableData: Area[], keys = ['label', 'value']): object[] {
  let p = []
  let c = []
  let a = []
  for (var i = 0; i < tableData.length; i++) {
    tableData[i][keys[0]] = tableData[i].name
    tableData[i][keys[1]] = tableData[i].id
    const deep = tableData[i].deep
    deep == 1 && p.push(tableData[i])
    deep == 2 && c.push(tableData[i])
    deep == 3 && a.push(tableData[i])
  }
  for (var i = 0; i < a.length; i++) {
    for (var j = 0; j < c.length; j++) {
      !c[j].children && (c[j].children = [])
      if (a[i].parentId == c[j].id) {
        c[j].children.push(a[i])
      }
    }
  }
  for (var i = 0; i < c.length; i++) {
    for (var j = 0; j < p.length; j++) {
      !p[j].children && (p[j].children = [])
      if (c[i].parentId == p[j].id) {
        p[j].children.push(c[i])
      }
    }
  }
  return p
}
// 获取地区数据
function getRegionDate() {
  uni.request({
    url: 'https://image.blacksilverscore.com/App/bbd3f87e-7e56-4b1d-8d53-97c3313391f4.json',
    data: {},
    header: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'X-Requested-With': 'XMLHttpRequest'
    },
    method: 'GET',
    sslVerify: true,
    success: ({ data, statusCode, header }) => {
      const rawData = partTree(data as Area[])

      // 只保留到市级，移除区级数据
      cityList.value = rawData.map((province) => ({
        ...province,
        children: province.children
          ? province.children.map((city) => ({
              id: city.id,
              name: city.name,
              parentId: city.parentId,
              deep: city.deep,
              label: city.label,
              value: city.value
              // 移除 children 属性
            }))
          : []
      }))
    },
    fail: (error) => {}
  })
}

const selectDefault = reactive<number[]>([])

// #region ********************* 打开地址选择器 ************************/
function openSelector() {
  selectorShow.value = !selectorShow.value
  if (selectorShow.value) {
    // 使用从 props 传入的地址或者组件内部的 getAdr
    const currentAddress = props.address || getAdr.value

    if (
      typeof currentAddress !== 'undefined' &&
      currentAddress !== null &&
      JSON.stringify(currentAddress) !== '{}'
    ) {
      const { provinceId, cityId } = currentAddress // 不再需要 districtId
      const pIdx = cityList.value.findIndex(
        (item: any) => item.id === provinceId
      )

      // 确保省份索引有效
      if (pIdx !== -1) {
        const cIdx = cityList.value[pIdx]?.children?.findIndex(
          (item: any) => item.id === cityId
        )

        // 设置默认选中值，只到市级（两个值）
        selectDefault.splice(
          0,
          selectDefault.length,
          pIdx,
          cIdx !== -1 ? cIdx : 0
        )
      } else {
        // 如果找不到省份，使用默认值
        selectDefault.splice(0, selectDefault.length, 0, 0)
      }
    } else {
      selectDefault.splice(0, selectDefault.length, 0, 0)
    }
  }
}
// 确定地址
function selectorConfirm(e: any) {
  // 将选择的数据转换为所需格式
  const selectedData = {
    provinceId: e[0]?.value,
    provinceName: e[0]?.label,
    cityId: e[1]?.value,
    cityName: e[1]?.label
  }
  let newAddress = {}
  let address = uni.getStorageSync('wzLocation')

  if (address.provinceId == selectedData.provinceId) {
    newAddress = { ...address, ...selectedData }
  } else {
    newAddress = { ...selectedData }
  }
  // 更新 getAdr 的值
  getAdr.value = newAddress

  // 可以通过 emit 传递给父组件
  emit('onAddressChange', newAddress)
}

//#endregion
//#region ********************* 搜索框 ************************/
const searchChange = (value: any) => {
  searchText.value = value
  emit('onSearch', value)
}

const debouncedHandleSearch = debounce((event) => {
  searchChange(event.detail.value)
}, 500)

// 根据模式修改logo
const getLogo = () => {
  const hyTpye = JSON.parse(uni.getStorageSync('hyType'))
  console.log(hyTpye)
  switch (hyTpye.id) {
    case 1:
      return log1
    case 4:
      return log4
    case 6:
      return log6
    default:
      break
  }
}

//#endregion

watch(
  () => props.address,
  (newVal, oldVal) => {
    if (newVal) {
      getAdr.value = newVal
    }
  },
  { deep: true }
)

// 如果 props.address 为空，尝试从本地存储获取
onMounted(() => {
  getRegionDate()
  if (!props.address || JSON.stringify(props.address) === '{}') {
    const storedAddress = uni.getStorageSync('currentAddress')
    if (storedAddress) {
      getAdr.value = storedAddress
    }
  }
})
</script>

<style lang="scss" scoped>
.rf-search-bar {
  padding: 20rpx 0;
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 10;

  .header {
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 12;
    height: 140rpx;

    .city-box {
      color: #000;
      margin-left: 20rpx;

      // padding-right: 30rpx;
      .icon {
        transition: transform 0.3s ease;

        &.rotate-icon {
          transform: rotate(180deg);
        }
      }
    }

    .icon-box {
      margin: 0 $uni-spacing-row-sm 0 0;
      color: $uni-text-color-inverse;

      .iconfont {
        font-weight: 400;
        font-size: 50rpx;
      }

      .logo {
        width: 45rpx;
        height: 45rpx;
        border-radius: 8rpx;
        margin-left: 10rpx;
      }
    }

    .input-box {
      flex: 1;
      height: 60rpx;
      line-height: 60rpx;
      background-color: #f0f0f0;
      border-radius: 30rpx;
      display: flex;
      align-items: center;
      // justify-content: space-between;
      // padding: 10rpx 20rpx;
      margin: 60rpx 20rpx;

      .wrapper {
        display: flex;
        align-items: center;

        font-size: $uni-font-size-sm + 2rpx;
        color: $uni-text-color-light;

        .iconfont {
          font-size: 34rpx;
          margin-right: $uni-spacing-row-sm;
        }
      }

      .input {
        width: 100%;
        padding-left: 18rpx;
        height: 28rpx;
        // color: #888;
        color: #000;
        font-size: 28rpx;
      }
    }
  }
}

.bg {
  &-primary {
    box-shadow: 0rpx 8rpx 16rpx 0rpx rgba(0, 0, 0, 0.07);
    background-color: rgba(255, 255, 255, 1);
    border-radius: 20rpx;
  }
}

.placeholder-box {
  width: 100%;
  margin-bottom: 40rpx;
  // padding-bottom: 40rpx;
  box-sizing: content-box;
}
</style>
